//
//  NewSearchViewController.m
//  礼物说
//
//  Created by dllo on 16/4/29.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "NewSearchViewController.h"

#define KSEARCHLiWuURL  [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/item?keyword=%@&limit=20&offset=%ld&sort=", words,(long)page]

#define KSEARCHGONGLVURL [NSString stringWithFormat:@"http://api.liwushuo.com/v2/search/post?keyword=%@&limit=20&offset=%ld&sort=", words,(long)page]

@interface NewSearchViewController ()<UISearchBarDelegate, UISearchResultsUpdating, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) BaseSearchController *searchController;
@property (nonatomic, retain) BaseCollectionView *collection;
@property (nonatomic, retain) BaseButton *liWuButton;
@property (nonatomic, retain) BaseButton *gongLvButton;
@property (nonatomic, retain) NSMutableArray *liWuArr;
@property (nonatomic, retain) NSMutableArray *GongLvArr;
/** 用于通知*/
@property (nonatomic, retain) BaseCollectionView *refurbishCollectionView;
@property (nonatomic, retain) BaseCollectionView *loadCollectionView;

@property (nonatomic, retain) BaseImageView *imgView;

@end

@implementation NewSearchViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)dealloc {
    [_searchController release];
    [_collection release];
    [_liWuButton release];
    [_gongLvButton release];
    [_liWuArr release];
    [_refurbishCollectionView release];
    [_loadCollectionView release];
    [_str release];
    [_words release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
#pragma mark - 创建左上角【返回 Button】
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(buttonAction)];
    self.navigationItem.leftBarButtonItem = button;
    [button release];
    self.tabBarController.tabBar.hidden = YES;
    
    [GiFHUD show];
    
    [self createButton];
    [self createSearch];
    [self createCollectionView];
    [self createImgView];
    [self notifacationCenter];
    
    [self dataHandleLiWuWords:_words page:0];
    [self dataHandleGongLvWords:_words Page:0];
    
    /** 网络请求*/
    self.liWuArr = [NSMutableArray array];
    self.GongLvArr = [NSMutableArray array];
}

#pragma mark - 刷新
- (void)notifacationCenter {
    /** 通知的接收者*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refurbishAction:) name:@"下拉刷新" object:nil];
    /** 通知的接受者*/
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadAction:) name:@"上拉加载" object:nil];
}
#pragma mark - 【刷新】通知响应
/** 下拉刷新，通知响应*/
- (void)refurbishAction:(NSNotification *)sender {
    
    NSString *judge = sender.userInfo[@"judge"];
    self.refurbishCollectionView = sender.userInfo[@"collection"];
    if ([judge isEqualToString:@"gongLv"]) {
        [self dataHandleGongLvWords:_words Page:0];
    }else {
        [self dataHandleLiWuWords:_words page:0];
    }
}
/** 上拉加载，通知响应*/
- (void)loadAction:(NSNotification *)sender {
    
    NSString *judge = sender.userInfo[@"judge"];
    NSString *str = sender.userInfo[@"page"];
    NSInteger page = [str integerValue];
    
    self.loadCollectionView = sender.userInfo[@"collection"];
    if ([judge isEqualToString:@"gongLv"]) {
        
        [self dataHandleGongLvWords:_words Page:page];
    }else{
        
        [self dataHandleLiWuWords:_words page:page];
    }

}

#pragma mark - 数据解析
#pragma mark - 礼物
- (void)dataHandleLiWuWords:(NSString *)words page:(NSInteger)page {
    [XRAFNetworkTool GETUrl:KSEARCHLiWuURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray *data = responseObject[@"data"][@"items"];
        NSMutableArray *array = [NSMutableArray array];
        array = [HotModel modelHandleWithArray:data];
        if (page == 0) {
            [_liWuArr removeAllObjects];
        }
        [_liWuArr addObjectsFromArray:array];
        [_collection reloadData];
        [GiFHUD dismiss];
        
        /** 刷新停止*/
        [_refurbishCollectionView.mj_header endRefreshing];
        [_loadCollectionView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}
#pragma mark - 攻略
- (void)dataHandleGongLvWords:(NSString *)words Page:(NSInteger)page {
    
    [XRAFNetworkTool GETUrl:KSEARCHGONGLVURL body:nil headFile:nil response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray *data = responseObject[@"data"][@"posts"];
        NSMutableArray *array = [NSMutableArray array];
        array = [ZhuanTiContentModel modelHandleWithArray:data];
        if (page == 0) {
            [_GongLvArr removeAllObjects];
        }
        [_GongLvArr addObjectsFromArray:array];
        
        if (_GongLvArr.count > 0) {
            _imgView.hidden = YES;
            [_collection reloadData];
        }else {
            _imgView.hidden = NO;
        }
        [GiFHUD dismiss];
        
        /** 停止刷新*/
        [_refurbishCollectionView.mj_header endRefreshing];
        [_loadCollectionView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - 当在没有搜索到的情况下显示占位图
- (void)createImgView {
    self.imgView = [[BaseImageView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT)];
    [self.view addSubview:_imgView];
    [_imgView release];
    _imgView.image = [UIImage imageNamed:@"b696845c1b47cb65260d75edf29a886b.jpg"];
}

#pragma mark - 创建【礼物，攻略 Button】
- (void)createButton{
    
    self.liWuButton = [BaseButton buttonWithType:UIButtonTypeCustom];
    _liWuButton.frame = CGRectMake(1, 0, kWIDTH / 2 - 1, kHEIGHTS(40));
    [self.view addSubview:_liWuButton];
    
    [_liWuButton setTitle:@"礼物" forState:UIControlStateNormal];
    [_liWuButton addTarget:self action:@selector(liWuButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_liWuButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    
    self.gongLvButton = [BaseButton buttonWithType:UIButtonTypeCustom];
    _gongLvButton.frame = CGRectMake(kWIDTH / 2 - 0, 0, kWIDTH / 2 - 1, kHEIGHTS(40));
    [self.view addSubview:_gongLvButton];
    
    [_gongLvButton setTitle:@"攻略" forState:UIControlStateNormal];
    [_gongLvButton addTarget:self action:@selector(gongLvButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_gongLvButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
#pragma mark - 礼物点击方法
- (void)liWuButtonAction:(UIButton *)button{
    
    _collection.contentOffset = CGPointMake(0, 0);
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.gongLvButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
#pragma mark - 攻略点击方法
- (void)gongLvButtonAction:(UIButton *)button{
    
    _collection.contentOffset = CGPointMake(kWIDTH, 0);
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.liWuButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
#pragma mark - [返回 点击方法]
- (void)buttonAction {
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 创建Search {
- (void)createSearch {
    /** 创建searchController*/
    self.searchController = [[BaseSearchController alloc] initWithSearchResultsController:nil];
    /** 签代理*/
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    /** 设置开始搜索时是否背景显示*/
    _searchController.dimsBackgroundDuringPresentation = NO;
    /** 设置开始搜索是否隐藏导航栏*/
    _searchController.hidesNavigationBarDuringPresentation = NO;
    /** 设置搜索的大小*/
    _searchController.searchBar.frame = CGRectMake(kWIDTHS(50), kHEIGHTS(5), kWIDTHS(200), kHEIGHTS(40));
    /** 添加在navigationbar 上*/
    self.navigationItem.titleView = self.searchController.searchBar;
    /** 释放*/
    [_searchController release];
    /** 设置搜索的背景颜色*/
    /** 搜索的提示字*/
    _searchController.searchBar.placeholder = @"请输入要搜索的关键字";
    /** 设置输入法的样式*/
    _searchController.searchBar.keyboardType = UIKeyboardAppearanceDefault;
    /** 搜索进入活跃状态*/
    [_searchController.searchBar setShowsCancelButton:YES animated:YES];
}

/** 获取所输入的文字*/
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
}

/** 点击搜索所触发的方法*/
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    /** 取消搜索的活动状态*/
    [searchBar setShowsCancelButton:NO animated:YES];
    /** 取消键盘的响应*/
    [searchBar resignFirstResponder];
    NSString *word = [searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [self dataHandleGongLvWords:word Page:0];
    [self dataHandleLiWuWords:word page:0];
    
    self.str = searchBar.text;
}

/** 取消按钮的点击方法*/
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 创建CollectionView 
- (void)createCollectionView {
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    layout.itemSize = CGSizeMake(kWIDTHS(372), kHEIGHTS(667));
    layout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, kHEIGHTS(40), kWIDTH, kHEIGHT) collectionViewLayout:layout];
//    self.collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: _collection];
    [_collection release];
    
    _collection.delegate = self;
    _collection.dataSource = self;
    /** 是否启用滚动*/
    _collection.scrollEnabled = NO;
    
    [_collection registerClass:[SearchGongLvCollectionViewCell class] forCellWithReuseIdentifier:@"SearchGongLv"];
    [_collection registerClass:[SearchLiWuCollectionViewCell class] forCellWithReuseIdentifier:@"SearchLiWu"];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 1) {
        SearchGongLvCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchGongLv" forIndexPath:indexPath];
        cell.searchStr = _str;
        cell.gongLvArr = _GongLvArr;
        [cell.collectionView reloadData];
        return cell;
    }else {
        SearchLiWuCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchLiWu" forIndexPath:indexPath];
        cell.searchStr = _str;
        cell.liWuArr = _liWuArr;
        [cell.collectionView reloadData];
        return cell;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
